"""
统一配置管理器 - JSON版本
支持JSON配置文件的读取、验证和管理
"""

import json
import os
from typing import Dict, Any, Optional
from pathlib import Path


class ConfigManagerJSON:
    """JSON配置文件管理器"""
    
    def __init__(self, config_file: str = "settings.json"):
        """
        初始化配置管理器
        
        Args:
            config_file: 配置文件路径
        """
        self.config_file = Path(config_file)
        self.config = self._load_default_config()
        self.load_config()
    
    def _load_default_config(self) -> Dict[str, Any]:
        """加载默认配置"""
        return {
            "ollama": {
                "host": "localhost",
                "port": 11434,
                "model": "qwen2.5-vl:7b",
                "timeout": 30,
                "max_retries": 3
            },
            "processing": {
                "mode": "standard",
                "batch_size": 10,
                "max_workers": 4,
                "enable_monitoring": False,
                "enable_resilient": False
            },
            "file_management": {
                "separate_files": False,
                "text_output_dir": "descriptions",
                "description_format": "txt",
                "overwrite_existing": False
            },
            "performance": {
                "enable_fast_mode": False,
                "cache_enabled": True,
                "parallel_processing": True,
                "memory_limit_mb": 1024
            },
            "ui": {
                "show_progress": True,
                "show_statistics": True,
                "log_level": "INFO"
            }
        }
    
    def load_config(self) -> bool:
        """
        从文件加载配置
        
        Returns:
            bool: 加载是否成功
        """
        try:
            if self.config_file.exists():
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    file_config = json.load(f)
                    # 合并配置，以文件配置为准
                    self._merge_config(self.config, file_config)
                return True
            else:
                # 如果配置文件不存在，创建默认配置文件
                self.save_config()
                return False
        except Exception as e:
            print(f"加载配置文件失败: {e}")
            return False
    
    def save_config(self) -> bool:
        """
        保存配置到文件
        
        Returns:
            bool: 保存是否成功
        """
        try:
            # 确保目录存在
            self.config_file.parent.mkdir(parents=True, exist_ok=True)
            
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=2, ensure_ascii=False)
            return True
        except Exception as e:
            print(f"保存配置文件失败: {e}")
            return False
    
    def _merge_config(self, base: Dict[str, Any], override: Dict[str, Any]) -> None:
        """递归合并配置字典"""
        for key, value in override.items():
            if key in base and isinstance(base[key], dict) and isinstance(value, dict):
                self._merge_config(base[key], value)
            else:
                base[key] = value
    
    def get(self, key_path: str, default: Any = None) -> Any:
        """
        获取配置值
        
        Args:
            key_path: 配置键路径，如 'ollama.host'
            default: 默认值
            
        Returns:
            配置值
        """
        keys = key_path.split('.')
        value = self.config
        
        try:
            for key in keys:
                value = value[key]
            return value
        except (KeyError, TypeError):
            return default
    
    def set(self, key_path: str, value: Any) -> None:
        """
        设置配置值
        
        Args:
            key_path: 配置键路径，如 'ollama.host'
            value: 配置值
        """
        keys = key_path.split('.')
        config = self.config
        
        # 导航到最后一级的父级
        for key in keys[:-1]:
            if key not in config:
                config[key] = {}
            config = config[key]
        
        # 设置值
        config[keys[-1]] = value
    
    def get_ollama_config(self) -> Dict[str, Any]:
        """获取Ollama配置"""
        return self.get('ollama', {})
    
    def get_processing_config(self) -> Dict[str, Any]:
        """获取处理配置"""
        return self.get('processing', {})
    
    def get_file_management_config(self) -> Dict[str, Any]:
        """获取文件管理配置"""
        return self.get('file_management', {})
    
    def get_performance_config(self) -> Dict[str, Any]:
        """获取性能配置"""
        return self.get('performance', {})
    
    def get_ui_config(self) -> Dict[str, Any]:
        """获取UI配置"""
        return self.get('ui', {})
    
    def update_ollama_config(self, **kwargs) -> None:
        """更新Ollama配置"""
        for key, value in kwargs.items():
            self.set(f'ollama.{key}', value)
    
    def update_processing_config(self, **kwargs) -> None:
        """更新处理配置"""
        for key, value in kwargs.items():
            self.set(f'processing.{key}', value)
    
    def update_file_management_config(self, **kwargs) -> None:
        """更新文件管理配置"""
        for key, value in kwargs.items():
            self.set(f'file_management.{key}', value)
    
    def validate_config(self) -> bool:
        """
        验证配置的有效性
        
        Returns:
            bool: 配置是否有效
        """
        try:
            # 验证Ollama配置
            ollama_config = self.get_ollama_config()
            if not all(key in ollama_config for key in ['host', 'port', 'model']):
                return False
            
            # 验证端口号
            port = ollama_config.get('port')
            if not isinstance(port, int) or port <= 0 or port > 65535:
                return False
            
            # 验证处理配置
            processing_config = self.get_processing_config()
            mode = processing_config.get('mode')
            if mode not in ['standard', 'fast', 'resilient']:
                return False
            
            return True
        except Exception:
            return False
    
    def get_config_summary(self) -> str:
        """获取配置摘要"""
        ollama_config = self.get_ollama_config()
        processing_config = self.get_processing_config()
        file_config = self.get_file_management_config()
        
        summary = f"""
配置摘要:
- Ollama服务器: {ollama_config.get('host')}:{ollama_config.get('port')}
- 模型: {ollama_config.get('model')}
- 处理模式: {processing_config.get('mode')}
- 文件分离: {'是' if file_config.get('separate_files') else '否'}
- 并行处理: {'是' if self.get('performance.parallel_processing') else '否'}
        """.strip()
        
        return summary
    
    def __str__(self) -> str:
        """返回配置的字符串表示"""
        return json.dumps(self.config, indent=2, ensure_ascii=False)


# 全局配置实例
config_manager = ConfigManagerJSON()


def get_config() -> ConfigManagerJSON:
    """获取全局配置管理器实例"""
    return config_manager


def reload_config() -> bool:
    """重新加载配置"""
    return config_manager.load_config()